import Storage from './storage'

export function getToken() {
  let now = Date.now() / 1000
  let tokenObj = null
  let token = ''
  tokenObj = Storage.getItem('token')
  if (tokenObj && tokenObj.expired_at > now) {
    token = tokenObj.token
  }
  return token
}
export function setToken(token, expired_at) {
  let tokenObj = {
    token,
    expired_at
  }
  return Storage.setItem('token', tokenObj)
}
/**
 * 获取oss上传配置
 * @returns {any}
 */
export function getPolicy() {
  let policy = JSON.parse(window.sessionStorage.getItem('ossPolicy'))
  let now = Math.floor(Date.parse(new Date()) / 1000)
  // 判断Policy是否失效
  if (policy.expire == undefined || now >= policy.expire) {
    let xmlhttp = null
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest()
    } else if (window.ActiveXObject) {
      xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
    }
    if (xmlhttp != null) {
      xmlhttp.open('GET', '/admin/upload/policy', false)
      xmlhttp.send(null)
      let res = eval('(' + xmlhttp.responseText + ')')
      window.sessionStorage.setItem('ossPolicy', JSON.stringify(res.data))
      policy = res.data
    } else {
      alert('Your browser does not support XMLHTTP.')
      policy = {}
    }
  }
  return policy
}

/**
 * uuid
 * @returns {string}
 */
export function uuid() {
  let d = new Date().getTime()
  if (window.performance && typeof window.performance.now === 'function') {
    d += performance.now() //use high-precision timer if available
  }
  return 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    let r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
  })
}

/**
 * 重命名文件
 * @param filename
 * @returns {string}
 */
export function fileRename(filename) {
  return uuid() + suffix(filename)
}

/**
 * 文件后缀名
 * @param filename
 * @returns {string}
 */
export function suffix(filename) {
  let pos = filename.lastIndexOf('.'),
    suffix = ''
  if (pos != -1) {
    suffix = filename.substring(pos)
  }
  return suffix
}

/**
 *
 * @param {*} key
 */
export function getConfig(file, key) {
  let keysAry = key.split('.')
  let c = require('@/config/' + file + '.js').default
  for (let k in keysAry) {
    c = c[keysAry[k]]
  }
  return c != undefined ? c : null
}
/**
 * 根据指定字段的值查找匹配的数组
 * @param {*} keyName
 * @param {*} keyValue
 * @param {*} arr
 */
export function getValueByKey(keyName, keyValue, arr) {
  for (let i in arr) {
    if (arr[i][keyName] == keyValue) {
      return arr[i]
    }
  }
}
/**
 * 获取get请求参数
 * @param {*} paraName
 * @param {*} url
 */
export function getUrlParam(paraName, url) {
  let arrObj = url.split('?')

  if (arrObj.length > 1) {
    let arrPara = arrObj[1].split('&')
    let arr

    for (let i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split('=')

      if (arr != null && arr[0] == paraName) {
        return arr[1]
      }
    }
    return ''
  } else {
    return ''
  }
}

/**
 * 递归查数组
 * @param {} value
 * @param {*} key
 * @param {*} array
 */
export function arrayFind(value, key, arr, childKey) {
  for (let i in arr) {
    let item = arr[i]

    if (item[key] == value) {
      return item[childKey]
    } else {
      if (item[childKey]) {
        return arrayFind(value, key, item[childKey], childKey)
      } else {
        return []
      }
    }
  }
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * 当前时间
 */
export function currentTime() {
  const x = ['日', '一', '二', '三', '四', '五', '六'];
  var myDate = new Date();
  myDate.getYear();        //获取当前年份(2位)
  myDate.getFullYear();    //获取完整的年份(4位,1970-????)
  myDate.getMonth();       //获取当前月份(0-11,0代表1月)
  myDate.getDate();        //获取当前日(1-31)
  myDate.getDay();         //获取当前星期X(0-6,0代表星期天)
  myDate.getTime();        //获取当前时间(从1970.1.1开始的毫秒数)
  myDate.getHours();       //获取当前小时数(0-23)
  myDate.getMinutes();     //获取当前分钟数(0-59)
  myDate.getSeconds();     //获取当前秒数(0-59)
  myDate.getMilliseconds();    //获取当前毫秒数(0-999)
  myDate.toLocaleDateString();     //获取当前日期
  var mytime=myDate.toLocaleTimeString();     //获取当前时间
  myDate.toLocaleString();        //获取日期与时间

  return `${myDate.getFullYear()}年${myDate.getMonth()}月${myDate.getDate()}日 星期${x[myDate.getDay()]} ${myDate.getHours()}:${myDate.getMinutes()}:${myDate.getSeconds()}`
}

export function currentHis() {
  const x = ['日', '一', '二', '三', '四', '五', '六'];
  var myDate = new Date();
  myDate.getYear();        //获取当前年份(2位)
  myDate.getFullYear();    //获取完整的年份(4位,1970-????)
  myDate.getMonth();       //获取当前月份(0-11,0代表1月)
  myDate.getDate();        //获取当前日(1-31)
  myDate.getDay();         //获取当前星期X(0-6,0代表星期天)
  myDate.getTime();        //获取当前时间(从1970.1.1开始的毫秒数)
  myDate.getHours();       //获取当前小时数(0-23)
  myDate.getMinutes();     //获取当前分钟数(0-59)
  myDate.getSeconds();     //获取当前秒数(0-59)
  myDate.getMilliseconds();    //获取当前毫秒数(0-999)
  myDate.toLocaleDateString();     //获取当前日期
  var mytime=myDate.toLocaleTimeString();     //获取当前时间
  myDate.toLocaleString();        //获取日期与时间

  console.log(myDate.getDay())
  return `${myDate.getHours()}:${myDate.getMinutes()}:${myDate.getSeconds()}`
}
